import { View, Video, Button, Text } from "@tarojs/components";
import { useEffect, useState } from "react";
import { AtSlider } from "taro-ui";
import Taro from "@tarojs/taro";
import "./index.scss";

let innerVideoContext: any; // 音频播放实例
function Videocom() {
  const [durationTime, setDurationTime] = useState<number>(0);
  const [currentTime, setCurrentTime] = useState<number>(0);

  const initAudioPlay = () => {
    innerVideoContext = Taro.createVideoContext("video");
  };

  useEffect(() => {
    initAudioPlay();
    return () => {
      innerVideoContext && innerVideoContext.pause();
      innerVideoContext && innerVideoContext.destroy();
      innerVideoContext = null;
      setDurationTime(0);
      setCurrentTime(0);
    };
  }, []);
  const test = () => {
    console.log(1);
  };

  const TimeUpdata = (e: any) => {
    setDurationTime(e.detail.duration);
    setCurrentTime(e.detail.currentTime);
  };

  // 音频进度控制
  const seekChange = (v: number) => {
    innerVideoContext.seek(v + 0.111111);
  };

  // 音频时间格式处理
  const formatTime = (time: number) => {
    if (time == null) return "-:-:-";

    const addZero = (n: number) => {
      if (n < 10) {
        return "0" + n;
      } else {
        return "" + n;
      }
    };
    let hour = Math.floor(time / 3600);
    let minute = Math.floor(Math.floor(time % 3600) / 60);
    let second = Math.floor(time % 60);

    return addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
  };

  return (
    <View className='video-menu'>
      <View className='player' onTouchStart={test}>
        <Video
          id='video'
          src='https://video.shipin520.com/videos/02/88/69/a_80Q3FSdagtTh1564028869.mp4'
          controls={false}
          // show-center-play-btn={false}
          onTimeUpdate={TimeUpdata}
        />
      </View>
      <View className='control'>
        <View className='play'>
          <Button>开始</Button>
        </View>
        <View className='time'>
          <Text>{formatTime(durationTime)}</Text>
        </View>
        <View className='slider'>
          <AtSlider
            step={1}
            value={currentTime}
            min={0}
            max={durationTime}
            activeColor='#fff'
            backgroundColor='rgba(255,255,255, .3)'
            blockSize={12}
            className='inner'
            onChange={seekChange}
          />
        </View>
        <View className='time'>
          <Text>{formatTime(currentTime)}</Text>
        </View>
      </View>
    </View>
  );
}

export default Videocom;
